<template>
    <panel-head :route="route" />
    <div class="btns">
        <el-button type="primary" :icon="Plus" @click="open(null)" size="small">新增</el-button>
    </div>

    <el-table :data="tableData.list" style="width: 100%">
        <el-table-column prop="id" label="id" />
        <el-table-column prop="name" label="昵称" />
        <el-table-column prop="permissionName" label="菜单权限" width="500px" />
        <el-table-column label="操作">
            <template #default="scope">
                <el-button type="primary" @click="open(scope.row)">编辑</el-button>
            </template>
        </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="pagination-info">
        <el-pagination
            v-model:currentPage="paginationData.pageNum"
            :page-size="paginationData.pageSize"
            :size="small"
            :background="false"
            layout="total, prev, pager, next, jumper"
            :total="tableData.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
    </div>

    <!-- 弹窗 -->
    <el-dialog v-model="dialogFormVisible" :before-close="beforeClose" :title="form.id ? '编辑权限' : '添加权限'" width="500">
        <el-form ref="formRef" :model="form" label-width="100px" label-position="left" :rules="rules">
            <el-form-item label="名称" prop="name">
                <el-input v-model="form.name" placeholder="请填写权限名称"></el-input>
            </el-form-item>
            <el-form-item v-show="false" prop="id">
                <el-input v-model="form.id" />
            </el-form-item>
            <el-form-item label="权限" prop="permissions">
                <el-tree ref="treeRef" :data="permissionData" style="max-width: 600px" node-key="id" show-checkbox :default-checked-keys="defaultKeys" :default-expanded-keys="[2]" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="confirm(formRef)">确定</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { nextTick, onMounted, reactive, ref } from 'vue'
import { userGetMenu, userSetMenu, menuList } from '@/api'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useRoute } from 'vue-router'

const route = useRoute()

// form数据
const form = reactive({
    id: '',
    name: '',
    permissions: '', // 选中的权限
})

// 权限树型菜单数据
const permissionData = ref([])
onMounted(() => {
    // 菜单数据
    userGetMenu().then(({ data }) => {
        console.log('菜单权限数据', data)
        permissionData.value = data.data
    })
    getListData()
})

// 打开弹窗
const open = (row = {}) => {
    console.log('row', row)
    dialogFormVisible.value = true
    // 弹窗打开form生成是异步的,用nextTick()
    nextTick(() => {
        if (row) {
            // 响应式数据合并（批量）
            Object.assign(form, { id: row.id, name: row.name })
            treeRef.value.setCheckedKeys(row.permission)
        }
    })
}
const paginationData = reactive({
    pageNum: 1,
    pageSize: 10,
})

const handleSizeChange = (val) => {
    paginationData.pageSize = val
    getListData()
}
const handleCurrentChange = (val) => {
    paginationData.pageNum = val
    getListData()
}

// 列表数据
const tableData = reactive({
    list: [],
    total: 0,
})
// 请求列表数据
const getListData = () => {
    menuList(paginationData).then(({ data }) => {
        if (data.code === 10000) {
            tableData.list = data.data.list
            tableData.total = data.data.total
        } else {
            ElMessage('获取列表失败', data.msg)
        }
    })
}
// 弹窗显示
const dialogFormVisible = ref(false)

// 关闭弹窗的回调
const beforeClose = () => {
    dialogFormVisible.value = false
    // .resetFields()重置表单同时清除所有验证错误状态
    formRef.value.resetFields()
    // tree选择重置
    treeRef.value.setCheckedKeys(defaultKeys)
}

const rules = reactive({
    name: [{ required: true, trigger: 'blur', message: '请输入权限名称' }],
})
// 选中权限
const defaultKeys = [4, 5] //默认选中的id
const treeRef = ref()
const formRef = ref()
// 表单提交
const confirm = async () => {
    if (!formRef.value) return

    // 验证表单
    await formRef.value.validate((valid, fields) => {
        if (valid) {
            // 获取到选择的checkbox的数据
            const permissions = JSON.stringify(treeRef.value.getCheckedKeys())

            userSetMenu({ id: form.id, name: form.name, permissions })
                .then(({ data }) => {
                    console.log(data)
                    if (data.code === 10000) {
                        ElMessage.success('操作成功')
                        dialogFormVisible.value = false
                        getListData() // 刷新列表
                        beforeClose()
                    } else {
                        ElMessage.error(data.msg || '操作失败')
                    }
                })
                .catch((error) => {
                    ElMessage.error('请求失败: ' + error.message)
                })
        }
    })
}
</script>
<style lang="less" scoped>
.btns {
    padding: 10px 0 10px 10px;
    background-color: #fff;
}
</style>
